package com.moyq5.wifi.joystick;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;

public class ClientActivity extends ConsoleActivityAbstract {
    private static final Console console = ConsoleFactory.get(ClientActivity.class);
    private BroadcastReceiver receiver;

    private IntentFilter intentFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        receiver = new WifiP2pClientReceiver(manager, channel, this);

        intentFilter = new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION);
        discoverPeers();
    }

    @Override
    int layoutId() {
        return R.layout.activity_client;
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, intentFilter);

    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }


    @SuppressLint("MissingPermission")
    private void discoverPeers() {
        console.debug("P2P 启动发现...");
        manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                console.info("P2P 启动发现，成功");
            }

            @Override
            public void onFailure(int reason) {
                console.info("P2P 启动发现，失败：%s", reason);
                ThreadKit.execute(() -> {
                    try {
                        Thread.sleep(3000);
                        discoverPeers();
                    } catch (InterruptedException ignored) {

                    }
                });
            }
        });
    }
}